import request from '@/utils/request'
import { LoginAction, RootThunkAction } from '@/types/store'
import { LoginForm, ApiResponse, Token } from '@/types/data'
import { removeToken, setToken } from '@/utils/storage'

export const login = (values: LoginForm): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>(
      '/authorizations',
      values
    )
    console.log(res)
    // token 持久化
    setToken(res.data.data)
    // 保存到 redux
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

export const getCode = (mobile: string) => {
  return async () => {
    await request.get(`/sms/codes/${mobile}`)
  }
}

export const logout = (): LoginAction => {
  removeToken()
  return {
    type: 'login/logout'
  }
}

export function saveToken (token: Token): LoginAction {
  setToken(token)
  return {
    type: 'login/token',
    payload: token
  }
}
